<template>
	<view class="login-page">
	  <!-- logo -->
	  <view class="logo-box">
		<image class="logo-img" src="/static/logo.png" mode="aspectFit" />
	  </view>

	  <!-- 输入框 -->
	<form class="loginForm" :model="loginForm" :rules="rules">
		  <view class="input-box">
			<view class="input-row">
			  <image class="input-icon" src="/static/login_phone.png" mode="aspectFit" />
			  <input class="input" v-model="loginForm.username" type="text" placeholder="请输入账号" />
			</view>
			<view class="input-row">
			  <image class="input-icon" src="/static/login_password.png" mode="aspectFit" />
			  <input class="input" type="password" v-model="loginForm.password" placeholder="请输入密码" />
			</view>
		  </view>
	  </form>

	  <!-- 登录按钮 -->
	  <view class="login-btn-box">
		<button class="login-btn" type="button" @click="onSubmit">登录</button>
		<view class="forget">
			<navigator class="toLogin" url="/pages/register/register" >注册</navigator >
			<navigator class="toForget forgetFont" url="/pages/user/forget/forget">忘记密码</navigator >
		</view>
	  </view>

	  <!-- 协议 -->
	  <view class="protocol-row">
		<image class="checked-icon" src="/static/check_box_checked.png" mode="aspectFit" />
		<text class="protocol-text">
			注册即代表您同意
			<text>《米多鱼s<text class="protocol-link" @click="navigatorInst(agreementintro.id)">{{ agreementintro.title }}</text>和<text class="protocol-link" @click="navigatorInst(privacyintro.id)">{{ privacyintro.title }}</text>》</text>
		</text>
	  </view>

    <view @click="onWxLogin" class="wx_login">
		<image src="/static/wechat.png" mode="aspectFit"></image>
		<!-- <button class="login-btn" >快捷登录</button> -->
    </view>
	</view>
  </template>

<script setup>
import { ref,reactive } from "vue"
import { useRoute } from "vue-router"
import { login,getWxToken } from "@/api/member.js"
import { onLoad } from '@dcloudio/uni-app';
import { getSysIntroByMark } from "@/api/sysIntro.js"
const privacyintro = reactive({
	title:"",
	id:0
})
const agreementintro = reactive({
	title:"",
	id:0
})
onLoad((options) => {
	console.log("onLoad");
	if((uni.getStorageSync("token") || '')){
		uni.switchTab({
			url: '/pages/index/index'
		});
	}
	
	getSysIntro();
});
const loading = ref(false);
const loginForm = ref({
	    username: '',
	    password:''
});
const route = useRoute();
const onSubmit = async()=>{
	let isValid = await validateForm();
	    // 如果表单数据不合法，则终止操作
	if (!isValid) return;
	loading.value = true;
	try {
		let result = await login(loginForm.value).then(res=>{
			console.log(res);
			if(res.token){
				uni.setStorageSync("token",res.token)
			}
			if (res) {
				uni.showModal({
					title: '提示',
					content: '登录成功',
					showCancel: false,
					success: () => {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}
				});
			} else {
				console.error('login failed:', res?.message || 'Unknown error');
			}
		});
	} catch (err) {
		console.error('请求失败：', err);
	}finally{
		loading.value = false;
	}
}

const getSysIntro = async()=>{
		await getSysIntroByMark({"mark":"privacy,reminder,agreement"}).then(result=>{
			console.log(result);
			Object.assign(agreementintro, result.find(item => item.mark === 'agreement'));
			Object.assign(privacyintro, result.find(item => item.mark === 'privacy'));
			console.log(privacyintro);
		})
	}

// 验证规则
const rules = {
	username: [
	  { required: true, message: '请输入账号号', trigger: 'change' }
	],
	password: [
	  { required: true, message: '请输入密码', trigger: 'change' }
	]
  };

const validateForm = async () => {
		const messages = Object.keys(rules).reduce((acc, key) => {
			const fieldRules = rules[key];
			const value = loginForm.value[key];
			fieldRules.forEach(rule => {
				if (rule.required && !value) {
					acc.push(rule.message);
					return;
				}
			});
			return acc;
		}, []);

		if (messages.length > 0) {
			uni.showModal({
				title: '提示',
				content: messages.join('\n'),
				icon: "none"
			});
			return false;
		}
		return true;
};
const onWxLogin = async () => {
	// 微信登录逻辑
	const loginRes = await uni.login({ provider: 'weixin' });

	console.log('loginRes返回:', loginRes);

    const code = loginRes.code;
      // 2. 获取用户加密数据
    if (loginRes.errMsg == 'login:ok') {
        //const { encryptedData, iv } = e.detail;
        // 3. 调用后端接口
        const res = await getWxToken({code:code,pid:uni.getStorageSync("mid") || 0 });
        console.log('微信登录返回:', res);	
		
		if(res.token){
			uni.setStorageSync("token",res.token)
			uni.showModal({
				title: '提示',
				content: '登录成功',
				showCancel: false,
			});

			uni.switchTab({ url: '/pages/index/index' });
		}
		
		 
		
    } else {
        uni.showToast({ title: '授权失败', icon: 'none' });
    }
}

const navigatorInst = (id)=>{
	uni.navigateTo({
		url:`/pages/index/instructions/instructions?id=${id}`
	});
}

  </script>

  <style scoped>
  .login-page {
	min-height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-bottom: 40rpx;
  }
  .logo-box {
	margin-top: 120rpx;
	margin-bottom: 80rpx;
	width: 100%;
	display: flex;
	justify-content: center;
  }
  .logo-img {
	width: 180rpx;
	height: 180rpx;
	border-radius: 16rpx;
	background: #4a90e2;
  }
  .input-box {
	width: 80vw;
	max-width: 600rpx;
	margin-bottom: 48rpx;
  }
  .input-row {
	display: flex;
	align-items: center;
	background: #f2f2f2;
	border-radius: 60rpx;
	height: 90rpx;
	margin-bottom: 32rpx;
	padding: 0 32rpx;
  }
  .input-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 18rpx;
  }
  .input {
	flex: 1;
	border: none;
	background: transparent;
	font-size: 30rpx;
	color: #333;
	outline: none;
  }
  .login-btn-box {
	width: 80vw;
	max-width: 600rpx;
	margin-bottom: 60rpx;
  }
  .login-btn {
	width: 100%;
	height: 90rpx;
	background: #4a90e2;
	color: #fff;
	font-size: 32rpx;
	border-radius: 60rpx;
	border: none;
	font-weight: bold;
	box-shadow: 0 4rpx 16rpx rgba(74,144,226,0.10);
  }
  .protocol-row {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 40rpx;
	margin-top: 20rpx;
  }
  .checked-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 10rpx;
  }
  .protocol-text {
	font-size: 22rpx;
	color: #888;
  }
  .protocol-link {
	color: #4a90e2;
  }
  .icp-row {
	width: 100%;
	display: flex;
	justify-content: center;
	margin-top: 40rpx;
  }
  .icp-text {
	font-size: 22rpx;
	color: #888;
  }
  .forget{
  	display:flex;
  	margin: 25rpx 0;
	font-size: 30rpx;
  }
  .toLogin,.toForget{
  	text-align: center;
  	flex: 1;
  }
  .forgetFont{
  	color: blue;
  }
  .loginForm{
	  margin: 0;
	  padding: 0;
  }
  .wx_login{
	  text-align: center;
	  height: 100rpx;
	  margin-top: -200rpx;
  }
  .wx_login image{
	  width: 100rpx;
  }
  .modal-mask {
  	position: fixed;
  	left: 0; top: 0; right: 0; bottom: 0;
  	background: rgba(0,0,0,0.35);
  	z-index: 999;
  	display: flex;
  	align-items: center;
  	justify-content: center;
  }
  
  .modal-box {
  	width: 80vw;
  	max-width: 600rpx;
  	background: #fff;
  	border-radius: 24rpx;
  	padding: 40rpx 24rpx 24rpx 24rpx;
  	box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.10);
  	display: flex;
  	flex-direction: column;
  	align-items: center;
  }
  .modal-title {
  	font-size: 32rpx;
  	font-weight: bold;
  	color: #222;
  	margin-bottom: 12rpx;
  }
  .modal-subtitle {
  	font-size: 24rpx;
  	color: #888;
  	margin-bottom: 18rpx;
  }
  .modal-content {
  	width: 100%;
  	font-size: 24rpx;
  	color: #333;
  	margin-bottom: 32rpx;
  }
  .modal-content text {
  	display: block;
  	margin-bottom: 12rpx;
  	line-height: 1.7;
  }
  .modal-btn-row {
  	display: flex;
  	width: 100%;
  	justify-content: space-between;
  	gap: 32rpx;
  }
  .modal-btn {
  	flex: 1;
  	text-align: center;
  	padding: 18rpx 0;
  	border-radius: 12rpx;
  	font-size: 28rpx;
  	font-weight: bold;
  }
  .modal-btn.reject {
  	background: #f6f7fb;
  	color: #4a90e2;
  	border: 2rpx solid #4a90e2;
  }
  .modal-btn.agree {
  	background: #4a90e2;
  	color: #fff;
  }
  </style>
